package com.study.boot.readinglist.config;

import com.study.boot.readinglist.entity.Reader;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import javax.annotation.Resource;

/**
 * 要求运行时激活production Profile，这样才能应用该配置，如果没有激活，则忽略该配置。
 * @author fangdengfu
 */
@Profile("production")
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private ReaderRepository readerRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 要求登陆这有READER角色
                .antMatchers("/").access("hasRole('READER')")
                .antMatchers("/**").permitAll()
                .and()

                // 设置登陆表单的路径
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error=true");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 自定义UserDetailsService
        auth.userDetailsService(username -> readerRepository.findById(username).orElse(new Reader()));
    }
}
